package com.smartnsoft.fractory;

import android.app.Activity;
import android.content.Intent;
import android.util.AndroidRuntimeException;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.smartnsoft.droid4me.app.ActivityController;
import com.smartnsoft.droid4me.app.AppPublics;
import com.smartnsoft.droid4me.app.ProgressHandler;
import com.smartnsoft.droid4me.app.Smarted;

/**
 * Gathers in one place the handling of the "Android 2.0" title bar
 * 
 * @author Willy Noel
 * @since 2011.05.24
 */
final class TitleBar
{

  static final class TitleBarAttributes
      extends ProgressHandler
  {

    private boolean enabledRefresh;

    private final View homeBlock;

    private final ImageButton home;

    private final TextView title;

    private final View action1Block;

    final ImageButton action1;

    private final View action2Block;

    final ImageButton action2;

    private final View action3Block;

    final ImageButton action3;

    private final View refreshBlock;

    private final View refreshSeparator;

    private final ImageButton refresh;

    private final ProgressBar refreshProgress;

    private final View searchBlock;

    private final ImageButton search;

    public TitleBarAttributes(Activity activity, View view)
    {
      homeBlock = view.findViewById(R.id.titleBarHomeBlock);
      home = (ImageButton) view.findViewById(R.id.titleBarHome);
      title = (TextView) view.findViewById(R.id.titleBarTitle);
      setTitle(activity.getTitle());
      action1Block = view.findViewById(R.id.titleBarAction1Block);
      action1 = (ImageButton) view.findViewById(R.id.titleBarAction1);
      action2Block = view.findViewById(R.id.titleBarAction2Block);
      action2 = (ImageButton) view.findViewById(R.id.titleBarAction2);
      action3Block = view.findViewById(R.id.titleBarAction3Block);
      action3 = (ImageButton) view.findViewById(R.id.titleBarAction3);
      refreshBlock = view.findViewById(R.id.titleBarRefreshBlock);
      refreshSeparator = view.findViewById(R.id.titleBarRefreshSeparator);
      refresh = (ImageButton) view.findViewById(R.id.titleBarRefresh);
      refreshProgress = (ProgressBar) view.findViewById(R.id.titleBarRefreshProgress);
      searchBlock = view.findViewById(R.id.titleBarSearchBlock);
      search = (ImageButton) view.findViewById(R.id.titleBarSearch);
      home.setImageResource(R.drawable.ic_title_home);
      setShowHome(-1, null);
      setShowRefresh(null);
      setShowSearch(null);
      setShowAction1(-1, null);
      setShowAction2(-1, null);
      setShowAction3(-1, null);
    }

    public void setTitle(CharSequence title)
    {
      this.title.setText(title);
    }

    private void setShowHome(int iconResourceId,
        View.OnClickListener onClickListener)
    {
      if (iconResourceId != -1)
      {
        homeBlock.setVisibility(View.VISIBLE);
        home.setImageResource(iconResourceId);
      }
      else
      {
        homeBlock.setVisibility(View.GONE);
        home.setImageDrawable(null);
      }
      home.setEnabled(onClickListener != null);
      home.setOnClickListener(onClickListener);
    }

    public void setShowAction1(int iconResourceId,
        View.OnClickListener onClickListener)
    {
      setShowAction(action1Block, action1, iconResourceId, onClickListener);
    }

    public void setShowAction2(int iconResourceId,
        View.OnClickListener onClickListener)
    {
      setShowAction(action2Block, action2, iconResourceId, onClickListener);
    }

    public void setShowAction3(int iconResourceId,
        View.OnClickListener onClickListener)
    {
      setShowAction(action3Block, action3, iconResourceId, onClickListener);
    }

    private void setShowAction(View actionBlockView, ImageButton actionButton,
        int iconResourceId, View.OnClickListener onClickListener)
    {
      if (iconResourceId != -1)
      {
        actionButton.setImageResource(iconResourceId);
      }
      else
      {
        actionButton.setImageDrawable(null);
      }
      actionBlockView.setVisibility(onClickListener != null ? View.VISIBLE
          : View.GONE);
      actionButton.setOnClickListener(onClickListener);
    }

    private void setShowRefresh(View.OnClickListener onClickListener)
    {
      enabledRefresh = onClickListener != null;
      refreshBlock.setVisibility(View.VISIBLE);
      refreshSeparator.setVisibility(enabledRefresh == true ? View.VISIBLE
          : View.INVISIBLE);
      refresh.setVisibility(enabledRefresh == true ? View.VISIBLE
          : View.INVISIBLE);
      refresh.setOnClickListener(onClickListener);
    }

    private void setShowSearch(View.OnClickListener onClickListener)
    {
      searchBlock.setVisibility(onClickListener != null ? View.VISIBLE
          : View.GONE);
      search.setOnClickListener(onClickListener);
    }

    public void onProgress(boolean isLoading)
    {
      toggleRefresh(isLoading);
    }

    public void toggleRefresh(boolean isLoading)
    {
      if (enabledRefresh == true)
      {
        refresh.setVisibility(isLoading == true ? View.INVISIBLE : View.VISIBLE);
      }
      refreshProgress.setVisibility(isLoading ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    protected void dismiss(Activity activity, Object progressExtra)
    {
      toggleRefresh(false);
    }

    @Override
    protected void show(Activity activity, Object progressExtra)
    {
      toggleRefresh(true);
    }

    public void setHome(int homeImageResourceId)
    {
      homeBlock.setVisibility(View.VISIBLE);
      home.setImageResource(homeImageResourceId);
      home.setEnabled(false);
    }

  }

  static interface TitleBarDiscarded
  {
  }

  static interface TitleBarRefreshFeature
  {
    void onTitleBarRefresh();
  }

  static interface TitleBarShowHomeFeature
  {
  }

  static interface TitleBarShowSearchFeature
  {
  }

  static interface TitleBarShowHomeAndSearchFeature
      extends TitleBarShowHomeFeature, TitleBarShowSearchFeature
  {
  }

  final static class TitleBarAggregate
      extends AppPublics.LoadingBroadcastListener
      implements View.OnClickListener
  {

    private final boolean customTitleSupported;

    private final Intent homeActivityIntent;

    private TitleBarAttributes attributes;

    private TitleBarRefreshFeature onRefresh;

    // private TitleBarShowSearchFeature onSearch;

    public TitleBarAggregate(Activity activity, boolean customTitleSupported,
        Intent homeActivityIntent)
    {
      super(activity, true);
      this.customTitleSupported = customTitleSupported;
      this.homeActivityIntent = homeActivityIntent;
    }

    TitleBarAttributes getAttributes()
    {
      return attributes;
    }

    private void setOnRefresh(
        final TitleBarRefreshFeature titleBarRefreshFeature)
    {
      this.onRefresh = titleBarRefreshFeature;
      attributes.setShowRefresh(titleBarRefreshFeature != null ? this : null);
    }

    private void setOnSearch(TitleBarShowSearchFeature titleBarSearchFeature)
    {
      // this.onSearch = titleBarSearchFeature;
      attributes.setShowSearch(titleBarSearchFeature != null ? this : null);
    }

    @Override
    protected void onLoading(boolean isLoading)
    {
      if (getActivity().getParent() == null)
      {
        // The activity is embedded
        attributes.toggleRefresh(isLoading);
      }
      else
      {
        AppPublics.LoadingBroadcastListener.broadcastLoading(getActivity(), getActivity().getParent().getClass(), isLoading, true);
      }
    }

    public void onClick(View view)
    {
      if (view == attributes.home && homeActivityIntent != null)
      {
        getActivity().startActivity(homeActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        getActivity().finish();
      }
      else if (view == attributes.refresh && onRefresh != null)
      {
        onRefresh.onTitleBarRefresh();
      }
      else if (view == attributes.search)
      {
        getActivity().onSearchRequested();
      }
    }

  }

  @SuppressWarnings("unchecked")
  public final static boolean onLifeCycleEvent(Activity activity,
      ActivityController.Interceptor.InterceptorEvent event,
      Intent homeActivityIntent, int defaultHomeResouceId,
      int defaultThemeResourceId)
  {
    if (event == ActivityController.Interceptor.InterceptorEvent.onSuperCreateBefore && !(activity instanceof TitleBar.TitleBarDiscarded))
    {
      activity.setTheme(defaultThemeResourceId);
      if (activity instanceof Smarted<?>)
      {
        boolean requestWindowFeature;
        if (activity.getParent() == null)
        {
          try
          {
            requestWindowFeature = activity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
          }
          catch (AndroidRuntimeException exception)
          {
            // This means that the activity does not support custom titles
            return true;
          }
        }
        else
        {
          requestWindowFeature = true;
        }
        // We test whether we can customize the title bar
        final TitleBarAggregate titleBarAggregate = new TitleBarAggregate(activity, requestWindowFeature, homeActivityIntent);
        final Smarted<TitleBarAggregate> smartedActivity = (Smarted<TitleBarAggregate>) activity;
        smartedActivity.setAggregate(titleBarAggregate);
        return true;
      }
    }
    else if (event == ActivityController.Interceptor.InterceptorEvent.onContentChanged && !(activity instanceof TitleBarDiscarded))
    {
      if (activity instanceof Smarted<?>)
      {
        final Smarted<TitleBarAggregate> smartedActivity = (Smarted<TitleBarAggregate>) activity;
        final TitleBarAggregate titleBarAggregate = smartedActivity.getAggregate();
        if (titleBarAggregate != null && titleBarAggregate.customTitleSupported == true && titleBarAggregate.attributes == null)
        {
          if (activity.getParent() == null)
          {
            activity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
            titleBarAggregate.attributes = new TitleBarAttributes(activity, activity.findViewById(R.id.titleBar));
            if (activity instanceof TitleBarRefreshFeature)
            {
              titleBarAggregate.setOnRefresh((TitleBarRefreshFeature) activity);
            }
            else
            {
              titleBarAggregate.setOnRefresh(null);
            }
            if (activity instanceof TitleBarShowHomeFeature)
            {
              titleBarAggregate.attributes.setShowHome(R.drawable.ic_title_home, titleBarAggregate);
            }
            else
            {
              titleBarAggregate.attributes.setShowHome(defaultHomeResouceId, null);
            }
            if (activity instanceof TitleBarShowSearchFeature)
            {
              titleBarAggregate.setOnSearch((TitleBarShowSearchFeature) activity);
            }
            else
            {
              titleBarAggregate.setOnSearch(null);
            }
          }
          smartedActivity.registerBroadcastListeners(new AppPublics.BroadcastListener[] { titleBarAggregate });
        }
      }
      return true;
    }
    return false;
  }

}
